package com.lw.mybatis.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

/**
 * @author Administrator
 * @version 1.0
 * @description:
 * @date 2022/3/3 11:17
 */
public class MyBatisUtil {

    private static ThreadLocal<SqlSession> sessionThreadLocal=new ThreadLocal<>();
    private static SqlSessionFactory sqlSessionFactory;
    public static SqlSession getSqlSession() throws Exception{
        if(sqlSessionFactory==null) {
            InputStream inputStream = Resources.getResourceAsStream("mybatis.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        }
        SqlSession sqlSession = sqlSessionFactory.openSession();
        sessionThreadLocal.set(sqlSession);
        return sqlSession;
    }

    public static <T> T getMapper(Class<T> mapperClass){
        SqlSession sqlSession = sessionThreadLocal.get();
        if(sqlSession==null){
            try {
                sqlSession = getSqlSession();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        T mapper = sqlSession.getMapper(mapperClass);
        return mapper;
    }

    public static void commit(){
        SqlSession sqlSession = sessionThreadLocal.get();
        if (sqlSession!=null) {
            sqlSession.commit();
        }
    }

    public static void rollback(){
        SqlSession sqlSession = sessionThreadLocal.get();
        if(sqlSession!=null){
            sqlSession.rollback();
        }
    }

    public static void close(){
        SqlSession sqlSession = sessionThreadLocal.get();
        if(sqlSession!=null){
            sqlSession.close();
            sessionThreadLocal.remove();
        }
    }
}
